using FastEndpoints;
using Ke.Bee.Shared.Abstractions;
using Ke.Bee.Shared.Models;
using Ke.Bee.Shared.Models.Tasks;
using Ke.Bee.Shared.Models.Uploads;
using Ke.Bee.Transcription.Abstractions;
using Ke.Bee.Transcription.Hubs;
using Ke.Bee.Transcription.Models;
using Microsoft.AspNetCore.SignalR;

namespace Ke.Paraleet.Hosts.Endpoints.Uploads;

/// <summary>
/// 文件上传处理
/// </summary>
public class UploadEndpoint(ILogger<UploadEndpoint> logger,
    IFileStorageService fileStorageService,
    ITranscriptionService transcriptionService,
    IHubContext<TranscriptionHub> hubContext)
    :
    EndpointWithoutRequest<ApiResponse<FileUploadResponse>>
{
    private readonly ILogger<UploadEndpoint> _logger = logger;
    /// <summary>
    /// 文件存储服务
    /// </summary>
    private readonly IFileStorageService _fileStorage = fileStorageService;
    /// <summary>
    /// 转写服务
    /// </summary>
    private readonly ITranscriptionService _transcriptionService = transcriptionService;
    /// <summary>
    /// SignalR 上下文
    /// </summary>
    private readonly IHubContext<TranscriptionHub> _hubContext = hubContext;

    public override void Configure()
    {
        Post("upload");
        Description(d => d
            .WithTags("文件上传")
            .WithName("FileUpload")
            //.Accepts<UploadRequest>("multipart/form-data")
            .Produces<ApiResponse<FileUploadResponse>>(200)
            .Produces<ErrorResponse>(400)
            .Produces<ErrorResponse>(500)
        );
        AllowAnonymous();
        AllowFileUploads();
        Options(x => x
            .WithTags("文件上传")
        );
    }

    public override async Task HandleAsync(CancellationToken ct)
    {
        // websocket 连接标识
        string? connectionId = Form["connectionId"];
        if (string.IsNullOrEmpty(connectionId))
        {
            AddError("连接标识为空");
            await Send.ErrorsAsync(500, ct);
            return;
        }

        // 创建任务 ID
        var taskId = Guid.NewGuid().ToString("N");

        // 发送进度更新
        await _hubContext.SendProgressUpdateAsync(connectionId, taskId, 1, "上传中", ct);

        try
        {
            var file = Files["file"];
            var storageResult = await _fileStorage.SaveTemporaryFileAsync(file, taskId, ct);
            if (!storageResult.Success)
            {
                AddError(storageResult.Message ?? "文件保存失败");
                await Send.ErrorsAsync(500, ct);
                return;
            }

            var d = storageResult.Data!;

            _logger.LogInformation("文件上传成功: {FileName}, TaskId: {TaskId}", file?.FileName, d.TaskId);

            // 发送上传结果
            await Send.OkAsync(ApiResponse<FileUploadResponse>.Ok(data: new(d.TaskId, d.FileName, d.CreatedAt)), ct);

            // 启动转写
            await _transcriptionService.ProcessFileAsync(new TranscriptionRequest(connectionId, d.TaskId, d.FileName, d.FilePath)
            {

            }, _hubContext, ct);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "文件上传处理失败");
            await Send.ErrorsAsync(500, ct);
        }
    }
}